package com.uzhie.web.controller.websocket;

import com.uzhie.web.anno.SocketController;
import com.uzhie.web.anno.SocketMapping;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by TangFei on 2018/8/9.
 * 获取bean注解
 */
public class ApplicationContextAware implements org.springframework.context.ApplicationContextAware {

    private Logger logger = Logger.getLogger(this.getClass());

    private WebsocketMethodInvoke<String> websocketMethodInvoke;

    public void setWebsocketMethodInvoke(WebsocketMethodInvoke<String> websocketMethodInvoke) {
        this.websocketMethodInvoke = websocketMethodInvoke;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("开始加载 websocket 请求处理方法");
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(SocketController.class);
        for (String key : beansWithAnnotation.keySet()) {
            Object o = beansWithAnnotation.get(key);
            Method[] methods = o.getClass().getMethods();
            for (Method method : methods) {
                boolean annotationPresent = method.isAnnotationPresent(SocketMapping.class);
                if (annotationPresent) {
                    websocketMethodInvoke.put(method.getAnnotation(SocketMapping.class).value(), new WebsocketClassMethod(o, method));
                    logger.info("mapping websocket requestMethod [" + method.getAnnotation(SocketMapping.class).value() + "] on method " + method.toString());
                }
            }
        }
        logger.info("加载 websocket 请求处理方法完成");
    }
}
